package com.example.framelib.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.*;
import android.util.Log;
import android.widget.Toast;

import com.example.framelib.BuildConfig;
import com.example.framelib.entity.VersionEntity;
import com.example.framelib.ui.view.CustomAlertDialog;
import com.example.framelib.ui.view.NumberProgressDialog;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

/**
 * Created by pamper on 2018/12/12.
 */

public class VersionUtil {

    private final  String TAG = getClass().getSimpleName();

    private static final VersionUtil instance = new VersionUtil();

    private CustomAlertDialog mCustomAlertDialog;
    private String downloadUrl;
    private NumberProgressDialog mNumberProgressDialog;
    private String dirName;
    private String apkName;
    private VersionEntity versionEntity;
    private Context context;

    private VersionUtil(){
    }

    public static VersionUtil getInstance(){
        return instance;
    }


    public void initFile(String dirName , String apkName , VersionEntity versionEntity , Context context){
        this.dirName = dirName;
        this.apkName = apkName + ".apk";
        this.versionEntity = versionEntity;
        this.context = context;
    }

    public void downloadApk(){
        showVersion(versionEntity , context);
    }

    public void showVersion(final VersionEntity version , final Context context) {
        if (version != null) {
            String remoteVersion = version.getVersion() + "";

            if (BuildConfig.VERSION_NAME.compareTo(remoteVersion) == -1) {
                mCustomAlertDialog = new CustomAlertDialog.Builder(context)
                        .setMessage("发现新版本，请及时更新")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                downloadUrl = version.getLinkUrl();

                                getNewVersion(downloadUrl , context);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                init();
                            }
                        }).create();
                mCustomAlertDialog.show();
            } else {
                init();
            }
        }
    }


    private void getNewVersion(String url , final Context context) {
        if (!NetworkUtils.isAvailable(context)) {
            Toast.makeText(context, "请检查网络", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mCustomAlertDialog.isShowing()) {
            mCustomAlertDialog.dismiss();
        }

        mNumberProgressDialog = new NumberProgressDialog(context);
        mNumberProgressDialog.show();
        Disposable disposable = RxDownload.getInstance(context)
                .download(url, apkName, getDownloadDir()) //只传url即可
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DownloadStatus>() {
                    @Override
                    public void accept(DownloadStatus status) throws Exception {
                        //DownloadStatus为下载进度
                        mNumberProgressDialog.setProgress((int) status.getPercentNumber());

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        //下载失败
                        android.util.Log.e(TAG, "下载失败: ");
                        mNumberProgressDialog.dismiss();
                        init();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //下载成功
                        android.util.Log.e(TAG, "下载成功: ");
                        mNumberProgressDialog.dismiss();
                        File apk = new File(getDownloadDir(), apkName);
                        if (Build.VERSION.SDK_INT < 23) {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
                            context.startActivity(intent);
                            ActivityManagerUtil.create().finishActivity();
                        } else {
                            if (apk.exists()) {
                                openFile(apk, context);
                            }
                        }

                    }
                });
    }

    private void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            try{
                Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG , e.getMessage());
            }


        }else{
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }

        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context , "没有找到打开此类文件的程序" , Toast.LENGTH_SHORT).show();
        }
    }

    public void init() {
        File apk = new File(getDownloadDir(), apkName);
        if (apk.exists()) {
            apk.delete();
        }
    }

    public String getDownloadDir() {
        File pbcDownload = new File(Environment.getExternalStorageDirectory(), dirName);
        if (!pbcDownload.exists()) {
            pbcDownload.mkdir();
        }
        return pbcDownload.getAbsolutePath();
    }
}
